#include "CapPackService.h"
#include "common_cap.h"
#include "Pacap/CaputerCapData.h"
#include "Pacap/PcapMsg.h"
#include "Pacap/PackType.h"
#include "SendMq/SendMq.h"
#include <memory>
#include "Poco/JSON/Object.h"
#include "Poco/JSON/Parser.h"
#include "HttpRequestParse/HttpRequest.h"


using namespace Pacap;

void CapPackService::start()
{
    try {
        CaputerCapData cap;
        cap.initPcap(CONF.getString("NetworkCard"),CONF.getString("filterStr"));
        cap.setPcapLoop(getData);
    }catch(Poco::Exception& e ) {
        std::cout << e.displayText() << std::endl;
        LOG.debug( "start capture error: %s",e.displayText() );
    }catch(Taiji::Except& e ){
        std::cout << e.what() << std::endl;
        LOG.debug( "start capture error: %s",std::string(e.what()) );
        exit(1);
    }


}

void CapPackService::getData(u_char *userArg, const pcap_pkthdr *h, const u_char *bytes)
{
    PackType raw( (uint8_t*)bytes,h->caplen);

    try{
        if( userArg == nullptr ){

        }

        LOG.debug( "rawData:%s",raw.toString() );
        PackType appdata = getApplication(raw);
        //如果数据长度为 0 返回
        if( appdata.length() == 0 ){
            return;
        }
        LOG.debug( "Application:%s",appdata.toString() );
        std::string data((char*)appdata.data(),appdata.length());
        std::cout << "+++++++++++++++++++++++原始数据:+++++++++++++++++++\n" << std::endl;
        std::cout << data << std::endl;
        std::cout << "--------------------------------------------------\n" << std::endl;
//        HttpRequest request(data);
    }catch (Taiji::ExceptProtocal & e){
        std::cout << "解析数据协议异常: " << e.what() << std::endl;
        LOG.error("解析数据协议异常:%s", std::string(e.what()));
        LOG.error( "发生错误的原数据:%s",raw.toString() );
    }catch ( Poco::Exception& e){
        std::cout << "发生异常:" << e.displayText() << std::endl;
        LOG.error("发生异常:%s", std::string(e.displayText()));
        LOG.error( "发生错误的原数据:%s",raw.toString() );
    }catch ( std::exception& e){
        std::cout << "发生异常:" << e.what() << std::endl;
        LOG.error("发生异常:%s", std::string(e.what()));
        LOG.error( "发生错误的原数据:%s",raw.toString() );
    }
}

PackType CapPackService::getApplication(const PackType &data)
{
    //获取有效的应用层数据
    std::shared_ptr<InetIpv4> pip(new InetIpv4);
    std::shared_ptr<InetTcp> ptcp( new InetTcp);

    PcapMsg msgParser;
    msgParser.setInternetIp(pip.get());
    msgParser.setTcp(ptcp.get());
    msgParser.unpack(data);
    return msgParser.getApplicationData();
}

